<template>
  <div class="forms">
    <el-button type="primary" class="addButton" @click="addButton"
      >添加</el-button
    >
    <el-dialog
      title="提示"
      :visible.sync="dialog.isShowDialog"
      width="60%"
      @opened="opened"
      @closed="closed"
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="cate">
          <el-form-item label="一级分类">
            <el-select
              v-model="ruleForm.first_cateid"
              placeholder="请选择"
              @change="firstChange(ruleForm.first_cateid)"
            >
              <el-option
                :label="item.catename"
                :value="item.id"
                v-for="item in cateListData"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类">
            <el-select v-model="ruleForm.second_cateid" placeholder="请选择">
              <el-option
                :label="item.catename"
                :value="item.id"
                v-for="item in firstListData.children"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="商品名称" prop="goodsname">
          <el-input v-model="ruleForm.goodsname"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="ruleForm.price"></el-input>
        </el-form-item>
        <el-form-item label="市场价格" prop="market_price">
          <el-input v-model="ruleForm.market_price"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="onChange"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog>
            <img width="100%" :src="imageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <div class="specs">
          <el-form-item label="商品规格">
            <el-select
              v-model="ruleForm.specsid"
              placeholder="请选择"
              @change="specsChange(ruleForm.specsid)"
            >
              <el-option
                :label="item.specsname"
                :value="item.id"
                v-for="item in specsListData"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类">
            <el-select
              v-model="ruleForm.specsattr"
              placeholder="请选择"
              multiple
            >
              <el-option
                :label="item"
                :value="item"
                v-for="(item, index) in attrs"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="是否新品" prop="isnew">
          <el-radio v-model="ruleForm.isnew" :label="1">是</el-radio>
          <el-radio v-model="ruleForm.isnew" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖" prop="ishot">
          <el-radio v-model="ruleForm.ishot" :label="1">是</el-radio>
          <el-radio v-model="ruleForm.ishot" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            :active-value="1"
            :inactive-value="2"
            inactive-color="#ff4949"
            v-model="ruleForm.status"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <div id="editor"></div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.isShowDialog = false">取 消</el-button>
        <el-button type="primary" @click="addGoods" v-if="gid == ''"
          >确 定</el-button
        >
        <el-button type="primary" @click="editGoods" v-else>确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 引入富文本编辑器
import E from "wangeditor";
import {
  getCateList,
  getSpecsList,
  getGoodsAdd,
  getGoodsInfo,
  getGoodsEdit,
} from "../../../request/api";
export default {
  props: ["dialog"],
  data() {
    return {
      gid: "",
      imageUrl: "",
      ruleForm: {
        first_cateid: "", // 一级分类id
        second_cateid: "", // 二级分类id
        goodsname: "", //商品名称
        price: "", //商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", //商品描述
        specsid: "", //商品规格编号
        specsattr: [], //商品规格属性
        isnew: "", //是否新品     1-是 2-否
        ishot: "", //是否热卖推荐 1-是 2-否
        status: 1, //状态1正常2禁用
      },
      // 商品分类列表数据
      cateListData: [],
      // 一级分类列表数据
      firstListData: [],
      // 商品规格数据
      specsListData: [],
      // 规格属性
      attrs: [],
    };
  },

  methods: {
    // 添加商品
    addGoods() {
      let isFile = false;
      if (this.ruleForm.img != "") {
        isFile = true;
      }
      // 将富文本编辑器的内容取出
      this.ruleForm.description = this.editor.txt.html();
      this.ruleForm.specsattr = JSON.stringify(this.ruleForm.specsattr);
      console.log(this.ruleForm);
      getGoodsAdd(this.ruleForm, isFile).then(
        (res) => {
          if (res.data.code == 200) {
            this.$message.success("添加成功");
            this.dialog.isShowDialog = false;
            // 刷新列表
            this.$emit("refreshList");
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    // 上传图片触发change事件调用
    onChange(file) {
      let imgType = ["image/png", "image/jpg", "image/jpeg", "image/gif"];
      if (imgType.indexOf(file.raw.type) == -1)
        return this.$message.error("图片格式不满足png/jpg/jpeg/gif格式");
      if (file.raw.size > 2 * 1024 * 1024)
        return this.$message.error("图片大小不能超过2MB");
      this.imageUrl = URL.createObjectURL(file.raw);
      // 将文件信息赋给添加表单的数据
      this.ruleForm.img = file.raw;
    },
    // 点击添加按钮
    addButton() {
      this.gid = "";
      this.dialog.isShowDialog = true;
    },
    // 获取商品分类列表数据
    getCateListData() {
      getCateList().then(
        (res) => {
          if (res.data.code == 200) {
            this.cateListData = res.data.list;
          }
        },
        (err) => err
      );
    },
    // 一级分类改变时触发
    firstChange(first_cateid) {
      this.ruleForm.second_cateid = "";
      let arr = this.cateListData.filter((item) => item.id == first_cateid);
      this.firstListData = arr[0];
    },
    // 获取商品规格数据
    getSpecsListData() {
      getSpecsList().then(
        (res) => {
          if (res.data.code == 200) {
            this.specsListData = res.data.list;
          }
        },
        (err) => err
      );
    },
    // 商品规格改变时触发
    specsChange(specsid) {
      this.ruleForm.specsattr = "";
      let arr = this.specsListData.filter((item) => {
        return item.id == specsid;
      });
      this.attrs = arr[0].attrs;
    },
    // 对话框打开时触发,用来展示富文本编辑器
    opened() {
      //创建编辑器对象
      this.editor = new E("#editor");
      this.editor.create();
      this.editor.txt.html(this.ruleForm.description);
    },
    // 对话框关闭时触发
    closed() {
      if (this.editor == null) return;
      this.editor.destroy();
      this.editor = null;
    },
    // 获取一个商品数据
    getOneGoodsData(id) {
      this.gid = id;
      getGoodsInfo({ id }).then(
        (res) => {
          if (res.data.code == 200) {
            this.ruleForm = res.data.list;
            this.ruleForm.first_cateid = "";
            this.ruleForm.second_cateid = "";
            this.ruleForm.specsid = "";
            this.dialog.isShowDialog = true;
          }
        },
        (err) => err
      );
    },
    // 编辑商品
    editGoods() {
      this.ruleForm.description = this.editor.txt.html();
      this.ruleForm.specsattr = JSON.stringify(this.ruleForm.specsattr);
      let obj = {
        id: this.gid,
        ...this.ruleForm,
      };
       let isFile = false;
      if (this.ruleForm.img != "") {
        isFile = true;
      }
      getGoodsEdit(obj,isFile).then(
        (res) => {
          if (res.data.code == 200) {
            this.$message.success("编辑成功");
            this.dialog.isShowDialog = false;
            // 刷新列表
            this.$emit("refreshList");
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
  },
  mounted() {
    this.getCateListData();
    this.getSpecsListData();
  },
};
</script>

<style scoped>
.addButton {
  margin-bottom: 20px;
}
.cate,
.specs {
  display: flex;
}
</style>